<!-- 订单结算页面 -->
<template>
  <view class="settlement">

    <view class="settlement-content">
      <view class="address-section">
        <u-cell-group>
          <u-cell
            title="收货地址"
            :value="addressText"
            is-link
            @click="goAddress"
          >
            <template #icon>
              <u-icon name="map" size="40" color="#00b578"></u-icon>
            </template>
            <template #value>
              <view class="address-info" v-if="currentAddress">
                <view class="user-info">
                  <text class="name">{{ currentAddress.receiverName }}</text>
                  <text class="phone">{{ currentAddress.receiverPhone }}</text>
                </view>
                <view class="detail">{{ fullAddress }}</view>
              </view>
              <text v-else class="no-address">请选择收货地址</text>
            </template>
          </u-cell>
        </u-cell-group>
      </view>

      <view class="order-section">
        <view class="section-title">
          <text>订单信息</text>
        </view>
        <u-cell-group>
          <u-cell title="商品合计" :value="'¥' + totalAmount" />
          <u-cell title="运费" :value="'¥' + deliveryFee" />
          <u-cell 
            title="可用积分" 
            :value="usePoints + '积分 = ¥' + pointsDiscount" 
            @click="handleUsePoints"
            is-link
          />
        </u-cell-group>
      </view>

      <view class="payment-section">
        <view class="section-title">
          <text>支付方式</text>
        </view>
        <u-cell-group>
          <u-cell title="微信支付" :value="'推荐'" @click="selectPayment('wechat')">
            <template #right-icon>
              <u-icon
                :name="selectedPayment === 'wechat' ? 'checkmark-circle-fill' : 'checkmark-circle'"
                :color="selectedPayment === 'wechat' ? '#00b578' : '#c8c9cc'"
                size="32"
              ></u-icon>
            </template>
          </u-cell>
          <!-- <u-cell title="余额支付" :value="`推荐`" @click="selectPayment('balance')" /> -->
        </u-cell-group>
      </view>
    </view>

    <view class="settlement-footer">
      <view class="price-info">
        <text class="label">实付金额：</text>
        <text class="amount">¥{{ finalAmount }}</text>
      </view>
      <u-button type="primary" color="#00b578" @click="submitOrder" :disabled="!canSubmit">提交订单</u-button>
    </view>

    <u-popup :show="payShow" mode="bottom" round="20" @close="payShow = false">
      <view class="pay-popup">
        <view class="popup-header">
          <text class="title">确认支付</text>
          <text class="amount">¥{{ finalAmount }}</text>
        </view>
        <view class="popup-content">
          <u-button type="primary" class="confirm-btn" @click="confirmPay">确认支付</u-button>
          <u-button type="info" plain class="cancel-btn" @click="payShow = false">取消</u-button>
        </view>
      </view>
    </u-popup>

    <!-- 积分使用弹窗 -->
    <u-popup :show="showPointsPopup" mode="bottom" round="20" @close="showPointsPopup = false">
      <view class="points-popup">
        <view class="popup-header">
          <text class="title">使用积分</text>
          <text class="points">可用积分：{{ availablePoints }}</text>
        </view>
        <view class="popup-content">
          <u-slider
            v-model="usePoints"
            :min="0"
            :max="availablePoints"
            :step="100"
            @change="handlePointsChange"
          ></u-slider>
          <view class="points-info">
            <text>使用{{ usePoints }}积分</text>
            <text>抵扣¥{{ (usePoints / 100).toFixed(2) }}</text>
          </view>
        </view>
        <view class="popup-footer">
          <u-button type="primary" @click="confirmUsePoints">确认使用</u-button>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { useAddressStore } from '@/store/addressStore'
import { useCartStore } from '@/store/cartStore'
import { usePointsStore } from '@/store/pointsStore'
import * as orderApi from '@/api/order'

const addressStore = useAddressStore()
const cartStore = useCartStore()
const pointsStore = usePointsStore()

const payShow = ref(false)
const showPointsPopup = ref(false)
const selectedPayment = ref('wechat')
const usePoints = ref(0)
const loading = ref(false)

// 获取当前选择的地址
const currentAddress = computed(() => addressStore.getCurrentAddress)

// 计算完整地址
const fullAddress = computed(() => {
  if (!currentAddress.value) return ''
  return `${currentAddress.value.province}${currentAddress.value.city}${currentAddress.value.district}${currentAddress.value.detailAddress}`
})

// 获取购物车商品总金额（不含运费）
const cartAmount = computed(() => {
  try {
    const items = cartStore.getSelectedItems || []
    let total = 0
    items.forEach(item => {
      const price = parseFloat(item?.price || 0)
      const quantity = parseInt(item?.quantity || 0)
      total += price * quantity
    })
    return total
  } catch (error) {
    return 0
  }
})

// 地址显示文本
const addressText = computed(() => {
  if (!currentAddress.value) return '请选择收货地址'
  return `${currentAddress.value.receiverName} ${currentAddress.value.receiverPhone}`
})

// 计算运费
const deliveryFee = computed(() => {
  try {
    const items = cartStore.getSelectedItems || []
    let totalDeliveryFee = 0
    items.forEach(item => {
      const itemDeliveryFee = parseFloat(item?.shippingFee || 0)
      const quantity = parseInt(item?.quantity || 0)
      totalDeliveryFee += itemDeliveryFee * quantity
    })
    
    return cartAmount.value >= 99 ? 0 : totalDeliveryFee
  } catch (error) {
    return 0
  }
})

// 获取可用积分
const availablePoints = computed(() => {
  return pointsStore.points || 0
})

// 积分抵扣金额
const pointsDiscount = computed(() => {
  return (usePoints.value / 100).toFixed(2)
})

// 商品总金额（不含运费）
const totalAmount = computed(() => {
  try {
    return cartAmount.value.toFixed(2)
  } catch (error) {
    return '0.00'
  }
})

// 最终支付金额（含运费）
const finalAmount = computed(() => {
  try {
    const total = cartAmount.value + deliveryFee.value - parseFloat(pointsDiscount.value || 0)
    return total.toFixed(2)
  } catch (error) {
    return '0.00'
  }
})

// 是否可以提交订单
const canSubmit = computed(() => {
  return currentAddress.value && cartAmount.value > 0
})

// 跳转到地址页面
const goAddress = () => {
  uni.navigateTo({
    url: '/pages/user/components/address'
  })
}

// 选择支付方式
const selectPayment = (type) => {
  selectedPayment.value = type
}

// 处理积分使用
const handleUsePoints = () => {
  showPointsPopup.value = true
}

// 积分滑块变化
const handlePointsChange = (value) => {
  usePoints.value = value
}

// 确认使用积分
const confirmUsePoints = () => {
  showPointsPopup.value = false
}

// 提交订单
const submitOrder = async () => {
  if (!currentAddress.value) {
    uni.showToast({
      title: '请选择收货地址',
      icon: 'none'
    })
    return
  }

  loading.value = true
  try {
    const orderData = {
      addressId: currentAddress.value.id,
      items: cartStore.getSelectedItems,
      totalAmount: cartAmount.value,
      deliveryFee: deliveryFee.value,
      pointsUsed: usePoints.value,
      pointsDiscount: Number(pointsDiscount.value),
      finalAmount: Number(finalAmount.value),
      paymentMethod: selectedPayment.value
    }

    const result = await orderApi.createOrder(orderData)

    if (result && result.code === 200) {
      try {
        await cartStore.removeSelectedItems()
        if (usePoints.value > 0) {
          await pointsStore.updatePoints(-usePoints.value)
        }
        payShow.value = true
      } catch (innerError) {
        payShow.value = true
      }
    } else {
      uni.showToast({
        title: (result && result.msg) || '创建订单失败',
        icon: 'none'
      })
    }
  } catch (error) {
    uni.showToast({
      title: '创建订单失败，请稍后重试',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

// 确认支付
const confirmPay = () => {
  uni.showToast({
    title: '支付成功',
    icon: 'success'
  })
  payShow.value = false
  // 修改跳转路径
  setTimeout(() => {
    uni.redirectTo({
      url: '/pages/order/order?status=1'  // 修改为正确的路径，并传入状态参数1表示待发货
    })
  }, 1500)
}

// 页面显示时获取必要数据
onShow(async () => {
  try {
    // 获取地址列表
    await addressStore.loadAddressList()

    // 如果没有选择地址，则使用默认地址
    if (!currentAddress.value) {
      const defaultAddress = addressStore.getAddressList.find(addr => addr.isDefault === 1)
      if (defaultAddress) {
        addressStore.setCurrentAddress(defaultAddress)
      }
    }
  } catch (error) {
    uni.showToast({
      title: '加载数据失败，请重试',
      icon: 'none'
    })
  }
})
</script>

<style lang="scss" scoped>
.settlement {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: calc(env(safe-area-inset-bottom) + 120rpx);


  .settlement-content {
    .address-section,
    .order-section,
    .payment-section {
      margin: 20rpx;
      border-radius: 12rpx;
      overflow: hidden;
      background-color: #fff;
      box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);

      .section-title {
        padding: 20rpx 30rpx;
        font-size: 30rpx;
        font-weight: bold;
        color: #333;
        border-bottom: 1rpx solid #f5f5f5;
      }
    }
  }

  .settlement-footer {
    position: fixed;
    bottom: env(safe-area-inset-bottom);
    left: 0;
    width: 100%;
    height: 100rpx;
    background-color: #fff;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 30rpx;
    box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);

    .price-info {
      .label {
        font-size: 28rpx;
        color: #666;
      }

      .amount {
        font-size: 36rpx;
        font-weight: bold;
        color: #ff8800;
      }
    }

    :deep(.u-button) {
      width: 240rpx;
      height: 80rpx;
      border-radius: 40rpx;
      font-size: 30rpx;
    }

    :deep(.u-button--disabled) {
      opacity: 0.6;
    }
  }

  .pay-popup {
    padding: 40rpx 30rpx;

    .popup-header {
      text-align: center;
      margin-bottom: 40rpx;

      .title {
        display: block;
        font-size: 32rpx;
        color: #333;
        margin-bottom: 20rpx;
      }

      .amount {
        font-size: 48rpx;
        font-weight: bold;
        color: #ff8800;
      }
    }

    .popup-content {
      .confirm-btn,
      .cancel-btn {
        width: 100%;
        height: 88rpx;
        border-radius: 44rpx;
        font-size: 32rpx;
        margin-bottom: 20rpx;

        &:active {
          transform: scale(0.98);
        }
      }
    }
  }

  .address-section {
    .address-info {
      .user-info {
        margin-bottom: 10rpx;
        
        .name {
          font-size: 28rpx;
          font-weight: bold;
          margin-right: 20rpx;
        }
        
        .phone {
          font-size: 28rpx;
          color: #666;
        }
      }
      
      .detail {
        font-size: 24rpx;
        color: #666;
        line-height: 1.4;
      }
    }
    
    .no-address {
      font-size: 28rpx;
      color: #999;
    }
  }

  .points-popup {
    padding: 40rpx 30rpx;

    .popup-header {
      text-align: center;
      margin-bottom: 40rpx;

      .title {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
        margin-bottom: 20rpx;
        display: block;
      }

      .points {
        font-size: 28rpx;
        color: #666;
      }
    }

    .popup-content {
      padding: 20rpx 0;

      .points-info {
        display: flex;
        justify-content: space-between;
        margin-top: 20rpx;
        font-size: 28rpx;
        color: #666;
      }
    }

    .popup-footer {
      margin-top: 40rpx;

      :deep(.u-button) {
        width: 100%;
        height: 88rpx;
        border-radius: 44rpx;
      }
    }
  }
}
</style>
